package com.yoda.youdianda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yoda.youdianda.common.ErrorResult;
import com.yoda.youdianda.common.R;
import com.yoda.youdianda.domain.YddCate;
import com.yoda.youdianda.domain.YddTag;
import com.yoda.youdianda.exception.BusinessException;
import com.yoda.youdianda.mapper.YddTagMapper;
import com.yoda.youdianda.service.YddTagService;
import com.yoda.youdianda.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class YddTagServiceImpl implements YddTagService {

    @Autowired
    private YddTagMapper tagMapper;

    @Override
    public Integer countTags() {
        return tagMapper.selectCount(new LambdaQueryWrapper<>());
    }

    @Override
    public boolean save(YddTag yddTag) {
        int count = tagMapper.insert(yddTag);
        return count > 0;
    }

    @Override
    public R<String> delete(int id) {
        YddTag YddTag = tagMapper.selectById(id);
        // 是默认数据,不可删除
        if ("1".equals(YddTag.getDefaultData())) {
            return R.success("系统默认数据，不允许删除", 100);
        }
        tagMapper.deleteById(id);
        return R.success("");
    }

    @Override
    public PageResult<YddTag> page(String tagname, String page, String limit) {
        int currentPage;
        int pageSize;
        if (StringUtils.isEmpty(page) || StringUtils.isEmpty(limit)) {
            throw new BusinessException(ErrorResult.paramNullError());
        }
        currentPage = Integer.parseInt(page);
        pageSize = Integer.parseInt(limit);
        LambdaQueryWrapper<YddTag> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!StringUtils.isEmpty(tagname), YddTag::getTagname, tagname);
        Page<YddTag> tagPage = new Page<>(currentPage, pageSize);
        tagMapper.selectPage(tagPage, wrapper);

        return new PageResult<>(currentPage, pageSize, (int) tagPage.getTotal(), tagPage.getRecords());
    }

    @Override
    public List<YddTag> list() {
        return tagMapper.selectList(new LambdaQueryWrapper<>());
    }

    @Override
    public R<YddTag> getById(String id) {
        YddTag yddTag = tagMapper.selectById(id);
        return R.success(yddTag);
    }

    @Override
    public R<String> updateById(YddTag yddTag) {
        tagMapper.updateById(yddTag);
        return R.success("修改成功!");
    }
}
